import { reactive, ref } from "vue";
import {
  getKnoDocGroupList,
  type KnoDocGroup
} from "@/views/domain/knowledge/api/knoDocGroup";
import {
  getKnoDocList,
  type KnoDoc
} from "@/views/domain/knowledge/api/knoDoc";

class KDGMixProvider {
  // 当前选择的命名空间
  curNamespace = ref<KnoDocGroup & { docs?: KnoDoc[] }>();

  nsList = ref<KnoDocGroup[]>([]);
  docList = ref<KnoDoc[]>([]);

  nsQuery = reactive({
    pageNum: 1,
    pageSize: 10,
    title: ""
  });

  docQuery = reactive({
    pageNum: 1,
    pageSize: 10,
    namespace: ""
  });

  uiOpt = reactive({
    docLoading: false,
    docNoMore: false,
    nsLoading: false,
    nsNoMore: false
  });

  async reloadDocList() {
    this.docList.value = [];
    this.docQuery.pageNum = 1;
    this.docQuery.pageSize = 10;
    this.uiOpt.docNoMore = false;
    this.uiOpt.docLoading = false;
    await this.loadMoreDoc();
  }

  //获取当前命名空间文档
  async loadMoreDoc() {
    if (this.uiOpt.docLoading || this.uiOpt.docNoMore) {
      return;
    }
    this.uiOpt.docLoading = true;
    const { ok, data } = await getKnoDocList({
      ...this.docQuery,
      namespace: this.curNamespace.value.namespace
    } as any);
    if (ok) {
      this.docList.value.push(...data.list);
      this.docQuery.pageNum++;

      if (data.list.length < this.docQuery.pageSize) {
        this.uiOpt.docNoMore = true;
      }
    }
    this.uiOpt.docLoading = false;
  }

  async reloadNsList() {
    this.nsList.value = [];
    this.nsQuery.pageNum = 1;
    this.nsQuery.pageSize = 10;
    this.uiOpt.nsNoMore = false;
    this.uiOpt.nsLoading = false;
    await this.loadMoreNs();
  }

  async loadMoreNs() {
    if (this.uiOpt.nsLoading || this.uiOpt.nsNoMore) {
      return;
    }
    this.uiOpt.nsLoading = true;
    const { ok, data } = await getKnoDocGroupList({
      ...this.nsQuery
    } as any);

    if (ok) {
      this.nsList.value.push(...data.list);
      this.nsQuery.pageNum++;

      if (data.list.length < this.nsQuery.pageSize) {
        this.uiOpt.nsNoMore = true;
      }
    }
    this.uiOpt.nsLoading = false;
  }
}

export default new KDGMixProvider();
